package org.example.mall.admin.service.manage.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mall.admin.constant.auth.AuthTypeConst;
import org.example.mall.admin.mapper.manage.AccountAuthMapper;
import org.example.mall.admin.model.entity.manage.Account;
import org.example.mall.admin.model.entity.manage.AccountAuth;
import org.example.mall.admin.service.manage.AccountAuthService;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 认证类型 服务实现类
 * </p>
 *
 * @author hzq
 * @since 2021-12-29
 */
@Service
public class AccountAuthServiceImpl extends ServiceImpl<AccountAuthMapper, AccountAuth> implements AccountAuthService {

    /**
     * 1、邮箱暂未被使用
     * 直接新增关联
     * 2、邮箱被其他用户使用
     * 删除该邮箱与前用户的关联
     * 添加新的关联
     */
    @Override
    public boolean editAccountEmail(Account account) {
        AccountAuth auth = new AccountAuth();
        auth.setAuthType(AuthTypeConst.EMAIL);
        auth.setPrincipal(account.getEmail());
        auth.setCredentials(AuthTypeConst.N_A);
        delRelation(account.getAccountId(), auth.getAuthType());
        return addRelation(account, auth);
    }

    @Override
    public boolean delRelation(Integer accountId, String authType) {
        LambdaQueryWrapper<AccountAuth> wrapper = Wrappers.<AccountAuth>lambdaQuery()
                .eq(AccountAuth::getAccountId, accountId)
                .eq(AccountAuth::getAuthType, authType);
        return remove(wrapper);
    }

    @Override
    public boolean delRelation(Integer accountId) {
        return remove(Wrappers.<AccountAuth>lambdaQuery().eq(AccountAuth::getAccountId, accountId));
    }

    /**
     * 1、手机号暂未被使用
     * 直接新增关联
     * 2、手机号被其他用户使用
     * 删除该手机号与前用户的关联
     * 添加新的关联
     */
    @Override
    public boolean editAccountPhone(Account account) {
        AccountAuth auth = new AccountAuth();
        auth.setAuthType(AuthTypeConst.PHONE);
        auth.setPrincipal(account.getPhone());
        auth.setCredentials(AuthTypeConst.N_A);
        delRelation(account.getAccountId(), auth.getAuthType());
        return addRelation(account, auth);
    }

    @Override
    public boolean addRelation(Account account, AccountAuth auth) {
        auth.setAccountId(account.getAccountId());
        auth.setUnionId(account.getUnionId());
        return save(auth);
    }

    @Override
    public AccountAuth getByCondition(String authType, String principal) {
        LambdaQueryWrapper<AccountAuth> wrapper = Wrappers.<AccountAuth>lambdaQuery()
                .eq(AccountAuth::getPrincipal, principal)
                .eq(AccountAuth::getAuthType, authType);
        return getOne(wrapper);
    }
}
